/*********************************************************************************
 *      Copyright:  (C) 2014 EAST
 *                  All rights reserved.
 *
 *       Filename:  recv.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(07/29/2014)
 *         Author:  fulinux <fulinux@sina.com>
 *      ChangeLog:  1, Release initial version on "07/29/2014 08:30:29 AM"
 *                 
 ********************************************************************************/

/* recv.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <msgque.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

static volatile int running = 1;

void sigterm(int signo)
{
    running = 0;
}

int main (int argc, char **argv)
{
    int i;
    struct timeval tv;
    msgque_t *msgque_r;
    msgque_t *msgque_w;

    /* 初始化消息队列 */
    msgque_r = msgque_init(1, O_RDWR);
    if(NULL == msgque_r){
        return -1;
    }
    printf ("msgque_r->msgid = %d\n", msgque_r->msgid);

    /* 初始化消息队列 */
    msgque_w = msgque_init(2, O_RDWR);
    if(NULL == msgque_w){
        return -1;
    }
    printf ("msgque_w->msgid = %d\n", msgque_w->msgid);

    signal(SIGTERM, sigterm);
    signal(SIGHUP, sigterm);
    signal(SIGINT, sigterm);

    msgque_w->msgbuf->mtype = 257;
    memset(msgque_w->msgbuf->mtext, 0x55, MSGSIZE);

    msgque_setdebug(msgque_r, FALSE);
    msgque_setdebug(msgque_w, FALSE);
    while(running){
        /* 发送消息队列 */
        printf("send...\n\n");
        if(-1 == msgque_write(msgque_w, IPC_NOWAIT)){
            continue;
        }

        for(;running;){
            tv.tv_sec = 3;
            tv.tv_usec = 0;
            printf("recv:\n");
            if(-1 == msgque_read_timeout(msgque_r, &tv)){
                continue;
            }else{
                printf("message mtype: %ld\n", msgque_r->msgbuf->mtype);
                printf("message mtext: ");
                for(i = 0; i < MSGSIZE; i++){
                    printf ("0x%x ", msgque_r->msgbuf->mtext[i]);
                }
                printf ("\n\n");
                sleep(3);
                break;
            }
        }
    }

    /* 注销消息队列 */
    if (-1 == msgque_exit(msgque_r)){
        perror ("MSGQUE EXIT\n");
        return -1;
    }

    /* 注销消息队列 */
    if (-1 == msgque_exit(msgque_w)){
        perror ("MSGQUE EXIT\n");
        return -1;
    }

    printf ("\nbye!\n");

    exit(EXIT_FAILURE);
} /* ----- End of main() ----- */
